package controllers

import (
	"ceshi0512/models"
	"ceshi0512/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type CeshiController struct {
	beego.Controller
}

func (c *CeshiController) Register() {
	username := c.GetString("username")
	password := c.GetString("password")

	pwd := pkg.Md5(password)
	var user models.User
	user.UserName = username
	user.Password = pwd
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "注册失败",
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "注册成功",
		}
		_ = c.ServeJSON()
	}
}

func (c *CeshiController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	var user models.User
	err := models.DB.Where("user_name=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "不存在此账号",
		}
		_ = c.ServeJSON()
		return
	}

	key := "user:login:err_count:" + username
	errCount, _ := models.Rdb.Get(models.Ctx, key).Int()
	if errCount >= 3 {
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "密码错误次数过多，请稍后重试",
		}
		_ = c.ServeJSON()
		return
	}

	if user.Password != pkg.Md5(password) {
		models.Rdb.Set(models.Ctx, key, errCount+1, time.Hour*2)
		c.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "密码错误",
		}
		_ = c.ServeJSON()
		return
	} else {
		c.Data["json"] = map[string]interface{}{
			"code": 200,
			"msg":  "登录成功",
		}
		_ = c.ServeJSON()
	}
}
